<?php
namespace app\api\controller;

use think\Request;
use think\Controller;
use think\Validate;
use think\Image;

class Common extends Controller{
    
    protected $request; //用来处理参数
    protected $validater; //用来验证数据/参数
    protected $params; //过滤后符合要求的参数
    protected $rules = array(
         'User' => array(
            'login' => array(
                'user_name' => ['require'],
                'user_pwd' => ['require', 'max' => 32, 'min' => 8],
            ),
            'register' => array(
                'user_name' => ['require'],
                'user_pwd' => ['require', 'max' => 32, 'min' => 8],
                'code' => ['require', 'number', 'length' => 6],
            ),
            'upload_head_img' => array(
                'user_id' => ['require', 'number'],
                'user_icon' => ['require', 'image', 'fileSize' => 5000000, 'fileExt' => 'jpg,png,bpm,jpeg'],
            ),
            'change_pwd' => array(
                'user_name' => ['require'],
                'user_old_pwd' => ['require', 'max' => 32, 'min' => 8],
                'user_pwd' => ['require', 'max' => 32, 'min' => 8],
            ),
            'find_pwd' => array(
                'user_name' => ['require'],
                'code' => ['require', 'number', 'length' => 6],
                'user_pwd' => ['require', 'max' => 32, 'min' => 8],
            ),
            'bind_phone'=>array(
                'user_id' => ['require','number'],
                'phone' => ['require','regex'=>'/^1[34578]\d{9}$/'],
                'code' => ['require','number','length:6']
                ),
            'bind_email' => array(
                'user_id' => ['require', 'number'],
                'email' => ['email'],
                'code' => ['require', 'number', 'length:6'],
            ),
            'bind_username'=>array(
                'user_id' => ['require', 'number'],
                'user_name' => ['require'],
                'code' => ['require', 'number', 'length:6'],               
                ),
            'set_nickname' => array(
                'user_id' => ['require', 'number'],
                'user_nickname' => ['require', 'chsDash'],
            ),
        ),
        'Article' => array(
            'add_article' => array(
                'article_title' => ['require', 'chsDash'],
                'article_uid' => ['require', 'number'],
            ),
            'article_list' => array(
                'user_id' => ['require', 'number'],
                'num' => ['number'],
                'page' => ['number'],
            ),
            'article_detail' => array(
                'article_id' => ['require', 'number'],
            ),
            'update_article' => array(
                'article_id' => ['require', 'number'],
            ),
            'del_article' => array(
                'article_id' => ['require', 'number'],
            ),
        ),
        'Common' => array(
            'get_code' => array(
                'username' => 'require',
                'is_exist' => 'require|number|length:1',
            ),
        ),
        'Code' => array(
            'get_code' => array(
                'username' => 'require',
                'is_exist' => 'require|number|length:1',
            ),
        ),   
    );
    protected function _initialize()
    {
        parent::_initialize();
        $this->request = Request::instance();
      //  $this->check_time($this->request->only(['time']));
       // $this->check_token($this->request->param());
        $this->params = $this->check_params($this->request->param(true));
    }
    
    /*
        验证请求是否超时
        @param |array| $arr [包含时间戳的参数数组]
        @return |json|  [检测结果] 
    */
    public function check_time($arr)
    {
        if(!isset($arr['time']) || intval($arr['time'])<=1){
            $this->return_msg(400,'时间戳不正确！');
        }
        if(time()-intval($arr['time'])>60){
            $this->return_msg(400,'请求超时！');
        }
    }
    /* api数据返回
    @param int code 状态码
    @param string msg 接口要返回的提示信息
    @param array $data 接口要返回的数据
    @return 最终要返回的json数据
    */
    public function return_msg($code,$msg='',$data=[])
    {
        $return_data['code'] = $code;
        $return_data['msg'] = $msg;
        $return_data['data'] = $data;
        //返回信息并终止脚本
        echo json_encode($return_data);die;
    }
    /**
     *  验证数据防止篡改数据
        @param array 全部请求参数
        @return json token验证结果
    */
    public function check_token($arr)
    {
        /*api传过来的token*/
        if(!isset($arr['token']) || empty($arr['token'])){
            $this->return_msg(400,'token不能为空！');
        }
        $app_token = $arr['token']; //api传过来的token
                /***服务器端生成token****/
        unset($arr['token']);
        $service_token = '';
        foreach($arr as $key => $value){
            $service_token = md5($value);
        }
        $service_token = md5('api_'.$service_token.'_api');
       // echo $service_token; die;
        /*对比token值*/
        if($app_token !== $service_token){
            $this->return_msg(400,'token值不正确！');
        }
        
    }
    /*
    * 验证参数 参数过滤
    *  @param array 除time，token外的所有参数
    * @return 合格的参数数组
    */
    public function check_params($arr)
    {   //获取参数的验证规则
        $rule = $this->rules[$this->request->controller()][$this->request->action()];
        //验证参数并返回错误
        $this->validater = new Validate($rule);
        if(!$this->validater->check($arr)){
            $this->return_msg(400,$this->validater->getError());
        };
        //正常通过验证
        return $arr;
        
    }
    /*检测用户名并返回用户名类别
        @parama string 用户名，可能是邮箱，也可能是手机号
        @return string 检测结果
    */
    public function check_username($username)
    {
        /* 判断是否为邮箱 */
        $is_email = Validate::is($username,'email')?1:0;
        /* 判断是否为手机号 */
        $is_phone = preg_match('/^1[34578]\d{9}$/',$username)?4:2;
        /* 最终结果 */
        $flag = $is_email+$is_phone;
        switch($flag){
            case 2:
                $this->return_msg(400,'邮箱或手机号不正确！');
                break;
            case 3:
                return 'email';
                break;
            case 4:
                return 'phone';
                break;
        }
        
    }
    
    /**
     * [检测该字段是否已经存在数据库中]
     * @param  [type] $value [description]
     * @param  [type] $type  [description]
     * @param  [type] $exist [description]
     * @return [type]        [description]
     */
    protected function check_exist($value, $type, $exist)
    {
        $type_num = $type == 'phone' ? 2 : 4;
        $flag = $type_num + $exist;

        $phone_res = db('user')->where('user_phone', $value)->find();
        $email_res = db('user')->where('user_email', $value)->find();

        switch ($flag) {
            case 2:
                if ($phone_res) {
                    $this->return_Msg(400, '此手机号已经被占用！');
                }
                break;
            case 3:
                if (empty($phone_res)) {
                    $this->return_Msg(400, '此手机号不存在！');
                }
                break;
            case 4:
                if ($email_res) {
                    $this->return_Msg(400, '此邮箱已经被注册！');
                }
                break;
            case 5:
                if (empty($email_res)) {
                    $this->return_Msg(400, '此邮箱不存在！');
                }
                break;
        }
    }   
        /**
     * [检查验证码是否输入正确]
     * @param  [string] $username [用户名(phone/email)]
     * @param  [int] $code     [验证码]
     * @return [json]           [执行返回信息]
     */
    public function check_code($username,$code)
    {
               //检测验证码时候输入正确
        $input_code = md5($username . '_' . md5($code));
        $last_code = session($username . '_code');

        if ($input_code !== $last_code) {
            $this->return_Msg('400', '验证码不正确，请重新输入！');
        }

        //检测是否超时
        $last_time = session($username . '_last_send_time');
        if (time() - $last_time > 600) {
            $this->return_Msg('400', '验证码超过600秒，请重新发送！');
        }

        //清除验证通过的验证码session
        session($username . '_code', null);
    }
        
    public function upload_file($file,$type='')
    {
        $info = $file->move(ROOT_PATH. 'public' . DS . 'uploads');
        if($info){
            $path = '/uploads/'.$info->getSaveName();
             //剪切图片
            if(!empty($type)){
                $this->image_edit($path,$type);
            }
            return str_replace('\\','/',$path);
            
        } else {
            $this->return_Msg(400,$file->getError());
        }
    }
    
        /**
     * [图片裁剪]
     * @param  [string] $path [原图片的绝对路径]
     * @param  [string] $type [图片的类型]
     * @return [null]
     */
    public function image_edit($path, $type)
    {
        $image = Image::open(ROOT_PATH . 'public' . $path);
        switch ($type) {
            case 'head_img':
                $image->thumb(200, 200, Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . $path);
                break;
            case 'other_img':
                break;
        }
    }
        
        
   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}